package cn.iocoder.yudao.module.book.controller.app.community;

import cn.hutool.core.io.IoUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.book.util.MinioUtils;
import cn.iocoder.yudao.module.book.service.minio.MinioService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "APP - 社区图片上传")
@RestController
@RequestMapping("/api/community")
public class AppCommunityUploadController {

        @Resource
        private MinioUtils minioUtils;

        @Resource
        private MinioService minioService;

        @PostMapping("/upload/image")
        @Operation(summary = "上传图片")
        public CommonResult<Map<String, Object>> uploadImage(
                        @Parameter(description = "图片文件") @RequestParam(value = "file", required = false) MultipartFile file,
                        @Parameter(description = "图片类型") @RequestParam(value = "type", defaultValue = "post_image") String type) {

                // 检查文件是否存在
                if (file == null || file.isEmpty()) {
                        return CommonResult.error(400, "请选择要上传的图片文件");
                }

                // 检查文件类型
                String contentType = file.getContentType();
                if (contentType == null || !contentType.startsWith("image/")) {
                        return CommonResult.error(400, "只支持上传图片文件");
                }

                // 检查文件大小（限制为5MB）
                if (file.getSize() > 5 * 1024 * 1024) {
                        return CommonResult.error(400, "图片文件大小不能超过5MB");
                }

                try {
                        // 使用MinIO上传文件
                        List<String> fileNames = minioUtils.upload(new MultipartFile[] { file });

                        if (fileNames.isEmpty()) {
                                return CommonResult.error(500, "文件上传失败");
                        }

                        String fileName = fileNames.get(0);

                        // 获取图片尺寸
                        int width = 0;
                        int height = 0;
                        try {
                                BufferedImage image = ImageIO.read(
                                                new ByteArrayInputStream(IoUtil.readBytes(file.getInputStream())));
                                if (image != null) {
                                        width = image.getWidth();
                                        height = image.getHeight();
                                }
                        } catch (Exception e) {
                                // 获取尺寸失败，使用默认值
                                width = 800;
                                height = 600;
                        }

                        // 构建MinIO访问URL
                        String baseUrl = "http://117.72.199.86:9000/image/"; // 根据配置文件中的MinIO地址
                        String fileUrl = baseUrl + fileName;

                        Map<String, Object> result = new HashMap<>();
                        result.put("url", fileUrl);
                        result.put("width", width);
                        result.put("height", height);
                        result.put("size", file.getSize());
                        result.put("originalName", file.getOriginalFilename());
                        result.put("fileName", fileName);
                        result.put("contentType", contentType);

                        return success(result);

                } catch (Exception e) {
                        return CommonResult.error(500, "文件上传失败：" + e.getMessage());
                }
        }

        @GetMapping("/upload/presigned-url")
        @Operation(summary = "获取预签名上传URL")
        public CommonResult<Map<String, Object>> getPresignedUploadUrl(
                        @Parameter(description = "文件名") @RequestParam("fileName") String fileName) {

                try {
                        // 生成唯一文件名
                        String fileExtension = "";
                        if (fileName.contains(".")) {
                                fileExtension = fileName.substring(fileName.lastIndexOf("."));
                        }
                        String uniqueFileName = "community/" + System.currentTimeMillis() + "_" +
                                        Math.random() * 1000 + fileExtension;

                        // 获取预签名URL
                        String presignedUrl = minioService.getPresignedUploadUrl(uniqueFileName);

                        // 构建访问URL
                        String baseUrl = "http://117.72.199.86:9000/image/";
                        String accessUrl = baseUrl + uniqueFileName;

                        Map<String, Object> result = new HashMap<>();
                        result.put("uploadUrl", presignedUrl);
                        result.put("accessUrl", accessUrl);
                        result.put("fileName", uniqueFileName);
                        result.put("originalName", fileName);
                        result.put("expiresIn", 3600); // 1小时有效期

                        return success(result);

                } catch (Exception e) {
                        return CommonResult.error(500, "生成上传URL失败：" + e.getMessage());
                }
        }

}
